<?php

namespace app\api\controller;

use addons\epay\library\Service;
use app\common\controller\Api;
use Exception;
use think\Db;
use Throwable;

/**
 * 订单管理
 */
class Order extends Api
{

    protected $noNeedLogin = ['notifyx'];
    protected $noNeedRight = '*';

    /**
     * 订单列表
     * @return void
     */
    public function lst()
    {
        $userId = $this->auth->id;
        $model = new \app\common\model\Order();
        $data = $model
            ->where("status", 1)
            ->where("user_id", $userId)
            ->order("id", "desc")
            ->paginate();
        $this->success("列表", $data);
    }

    /**
     * 创建订单
     * @ApiMethod (POST)
     * @param string $course_id 课程ID
     * @param string $name 姓名
     * @param string $school 学校
     * @param string $age 年龄
     * @param string $phone 家长联系电话
     * @param string $grade 班级
     */
    public function create()
    {
        $params = $this->request->post(['course_id', 'name', 'school', 'age', 'phone', 'grade']);
        $validate = new \app\api\validate\Order();
        try {
            $validate->scene("create")->check($params);
        } catch (Throwable $e) {
            $this->error($e->getMessage());
        }
        $result = '';

//         启动事务
        Db::startTrans();
        try {
            $userId = $this->auth->getUser()['id'];
            $campus_id = $this->auth->getUser()['campus_id'];
            $courseModel = new \app\common\model\Course();
            $course = $courseModel->where("id", $params['course_id'])->findOrFail();
            $data = [
                'price' => $course['price'],
                'real_price' => $course['price'],
                'order_sn' => get_order_sn("order"),
                'user_id' => $userId,
                'status' => 0,
                'course_id' => $params['course_id'],
                'name' => $params['name'],
                'school' => $params['school'],
                'age' => $params['age'],
                'phone' => $params['phone'],
                'grade' => $params['grade'],
                'campus_id' => $campus_id

            ];
            $model = new \app\common\model\Order();
            $model->save($data);

            $notifyurl = $this->request->root(true) . '/api/order/notifyx/paytype/wechat';
            $openId = Db::name("third")->where("user_id", $userId)->value("openid");
            $result = Service::submitOrder($data['real_price'], $data['order_sn'], 'wechat', "课程购买", $notifyurl, null, 'mp', $openId);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success("", ['pay' => $result]);
    }

    private function orderPaySuccess($orderSn)
    {
        $model = new \app\common\model\Order();
        $order = $model
            ->where("order_sn", $orderSn)
            ->where('status', 0)
            ->find();
        $order->status = 1;
        $order->pay_time = time();
        $order->save();
        $courseModel = new \app\common\model\Course();
        $courseModel->where("id", $order['course_id'] ?? 0)->setInc("number");
    }

    /**
     * 支付成功，
     */
    public function notifyx()
    {
        $paytype = $this->request->param('paytype');
        $pay = Service::checkNotify($paytype);
        if (!$pay) {
            return json(['code' => 'FAIL', 'message' => '失败'], 500, ['Content-Type' => 'application/json']);
        }

        // 获取回调数据，V3和V2的回调接收不同
        $data = Service::isVersionV3() ? $pay->callback() : $pay->verify();

        try {
            //微信支付V3返回和V2不同
            if (Service::isVersionV3() && $paytype === 'wechat') {
                $data = $data['resource']['ciphertext'];
                $data['total_fee'] = $data['amount']['total'];
            }

            \think\Log::record($data);
            //获取支付金额、订单号
            $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            $out_trade_no = $data['out_trade_no'];
            $this->orderPaySuccess($out_trade_no);

            \think\Log::record("回调成功，订单号：{$out_trade_no}，金额：{$payamount}");

            //你可以在此编写订单逻辑
        } catch (Exception $e) {
            \think\Log::record("回调逻辑处理错误:" . $e->getMessage(), "error");
        }

        //下面这句必须要执行,且在此之前不能有任何输出
        if (Service::isVersionV3()) {
            return $pay->success()->getBody()->getContents();
        } else {
            return $pay->success()->send();
        }
    }


}